package thread.timer;

import java.util.concurrent.PriorityBlockingQueue;

public class MyTimer {
    //任务类 描述任务和任务的delay时间
    static class Task implements Comparable<Task> {
        //任务
        private Runnable command;
        //delay
        private long time;

        public Task(Runnable command, long time) {
            this.command = command;
            //时间是在现在的时间的基础上加上delay
            this.time = System.currentTimeMillis() + time;
        }

        public void run() {
            command.run();
        }

        @Override
        public int compareTo(Task o) {
            return (int) (this.time - o.time);
        }
    }

    //优先级阻塞队列 核心结构
    //队首存放的是最近要执行的任务 time最小
    private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue();

    public void schedule(Runnable command, long time) {
        //生成一个任务 然后放进去优先级队列
        Task task = new Task(command, time);
        queue.put(task);

        //有新任务来了 唤醒work 检测是否有更新的工作需要执行
        synchronized (lock) {
            lock.notify();
        }
    }

    private Object lock = new Object();

    public MyTimer() {
        //在构造方法中来一个扫面线程 一直扫描队首的元素是否到了执行时间
        Thread work = new Thread(() -> {
            while (true) {
                try {
                    synchronized (lock) {
                        Task task = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (task.time > curTime) {
                            // 时间还没到, 就把任务再塞回去
                            queue.put(task);
                            // 等待一段时间

                            lock.wait(task.time - curTime);

                        } else {
                            // 时间到了, 可以执行任务
                            task.run();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        });
        work.start();
    }

    //测试代码
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("我有第一个任务！");
            }
        }, 3000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("我有第二个任务！");
            }
        }, 1000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("我有第三个任务！");
            }
        }, 2000);
    }
}
